﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarolLib.Configuration;
using System.Xml;

namespace CarolLib.Control
{
    public class ModulesConfiguration : ConfigurationBase
    {
        Dictionary<string, MdiUserControl> modules;

        string defaultModuleName = string.Empty;

        public MdiUserControl DefaultModule
        {
            get
            {
                if (Modules.ContainsKey(defaultModuleName))
                    return Modules[defaultModuleName];
                return null;
            }
        }

        public ModulesConfiguration()
            : base()
        {
            modules = new Dictionary<string, MdiUserControl>();
        }

        public ModulesConfiguration(XmlNode node)
            : base()
        {
            foreach (XmlNode child in node.ChildNodes)
            {
                switch (child.Name.ToLower())
                {
                    case "modules":
                        XmlAttribute xa = child.Attributes["Default"];
                        if (xa != null && (!string.IsNullOrEmpty(xa.Value)))
                        {
                            this.defaultModuleName = xa.Value;
                        }
                        LoadModules<MdiUserControl>(child, ref modules, child);
                        break;
                }
            }
        }

        public static ModulesConfiguration GetConfig()
        {
            return GetConfig<ModulesConfiguration>("mdi");
        }

        public Dictionary<string, MdiUserControl> Modules
        {
            get { return modules; }
        }

        public void UnloadModules()
        {
            foreach (MdiUserControl module in modules.Values)
                module.Unload();

            modules.Clear();
        }

        public IEnumerable<T> GetModules<T>() where T : MdiUserControl
        {
            return modules.Values.Where(m => m is T).Cast<T>();
        }
    }
}
